package com.guldan.thrall.common.response;

import com.guldan.core.response.ResponseJsonAspect;
import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;

public class HeaderWithResponseJsonAspect extends ResponseJsonAspect {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public void before(JoinPoint jp) throws IOException {
        super.before(jp);

        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes()).getRequest();


        HttpServletRequest req = (HttpServletRequest) request;

        /*int length = req.getContentLength();
        if (length > 0) {
            BufferedRequestWrapper bufferedRequest = new BufferedRequestWrapper(req, length);

            InputStream is = bufferedRequest.getInputStream();
            byte[] content = new byte[length];

            int pad = 0;
            while (pad < length) {
                pad += is.read(content, pad, length);
            }

            this.logger.info("postdata: " + content.toString());

            request = bufferedRequest;
        }
*/

        String reqParamsString = (String) request.getAttribute(reqParamsStringKey);
        String authCode = request.getHeader("User-Code");
        reqParamsString += ",with User-Code:" + StringUtils.trimToEmpty(authCode);
        request.setAttribute(reqParamsStringKey, reqParamsString);
    }

}
